<template>
  <div class="container">
    <div class="todo-list">
      <!-- header  -->
      <todo-header
        :title="title"
        @click="addTodos"
      />
      <!-- list -->
      <todo-list :todos="todos">
        <todo-item
          v-for="todo in todos"
          :key="todo.id"
          :todo="todo"
          @change="editTodos"
        />
      </todo-list>
      <!-- footer -->
      <todo-footer
        :finishedNum="finishedNum"
        :unFinishedNum="unFinishedNum"
        :isSwitch="isSwitch"
        @change="selectAllAndReverse"
        @click="deleteTodos"
      />
    </div>
  </div>
</template>
<script>
import Header from './components/Header.vue'
import List from './components/List.vue'
import Footer from './components/Footer.vue'
import Item from './components/Item.vue'
import * as http from '@/api/todos.js'
export default {
  computed: {
    finishedNum() {
      return this.todos.filter((v) => v.completed).length
    },
    unFinishedNum() {
      return this.todos.filter((v) => !v.completed).length
    },
    isSwitch() {
      return this.todos.every((v) => v.completed)
    }
  },
  data() {
    return {
      title: '待办事项',
      todos: []
    }
  },
  created() {
    this.getTodos()
  },
  methods: {
    async getTodos() {
      const res = await http.getTodos()
      this.todos = res
    },
    async addTodos(title) {
      // this.todos.push({
      //   id: Date.now(),
      //   title,
      //   completed: false
      // })
      await http.addTodos({
        id: Date.now(),
        title,
        completed: false
      })
      // 重新请求获取最新的数据达到刷新的效果
      this.getTodos()
    },
    async editTodos(completed, id) {
      // console.log(completed, id)
      // const newTodos = this.todos.filter((v) => {
      //   if (v.id === id) {
      //     v.completed = !completed
      //   }
      //   return v
      // })

      // // console.log(newTodos)
      // this.todos = newTodos
      await http.editTodos(!completed, id)
      this.getTodos()
    },
    selectAllAndReverse(isSwitch) {
      // console.log(isSwitch)
      this.todos.forEach(async (v) => {
        // v.completed = isSwitch
        await http.editTodos(isSwitch, v.id)
      })
      this.getTodos()
    },
    deleteTodos() {
      this.todos.forEach(async (v) => {
        if (v.completed) await http.deleteTodos(v.id)
      })
      this.getTodos()
    }
  },
  components: {
    'todo-header': Header,
    'todo-list': List,
    'todo-footer': Footer,
    'todo-item': Item
  }
}
</script>
<style lang="scss" scoped>
@import url(../../../node_modules/bootstrap/dist/css/bootstrap.css);
.todo-list {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #ddd;
}
</style>
